package com.muqi.app.qlearn.fragments;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.charts.PieChart;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.Legend.LegendDirection;
import com.github.mikephil.charting.components.Legend.LegendPosition;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.muqi.app.network.http.GlideImageUtils;
import com.muqi.app.network.http.MyAsyncHttp;
import com.muqi.app.network.http.NetWorkUtils;
import com.muqi.app.network.http.ParamsUtils;
import com.muqi.app.network.http.ResponseUtils;
import com.muqi.app.network.http.MyAsyncHttp.AsyncCallBackListener;
import com.muqi.app.network.http.MyAsyncHttp.RESULTCODE;
import com.muqi.app.project.contants.MContants;
import com.muqi.app.project.contants.NetWorkApi;
import com.muqi.app.project.utils.NumberFormatUtil;
import com.muqi.app.project.utils.ShowToast;
import com.muqi.app.qlearn.adapter.HomeWorkAdapter;
import com.muqi.app.qlearn.modles.Banner;
import com.muqi.app.qlearn.modles.GrowRewardAndMoveInfo;
import com.muqi.app.qlearn.modles.HomeWorkBean;
import com.muqi.app.qlearn.modles.HomeWorkFile;
import com.muqi.app.qlearn.modles.LastRecord;
import com.muqi.app.qlearn.student.BaseChildFragment;
import com.muqi.app.qlearn.student.BaseFragment;
import com.muqi.app.qlearn.student.MenuActivity;
import com.muqi.app.qlearn.student.R;
import com.muqi.app.qlearn.student.ui.HomeWorkStatisticActivity;
import com.muqi.app.qlearn.ui.MyHomeWkDetailsActivity;
import com.muqi.app.qlearn.ui.MyHomeWorkActivity;
import com.muqi.app.user.db.ChildBean;
import com.muqi.app.user.widget.SelectableRoundedImageView;
import com.muqi.app.widget.pulltorefresh.XListView;
import com.muqi.app.widget.scanpicture.ScanPictureActivity;

@SuppressLint("InflateParams")
public class AcademicLevelFragment extends BaseChildFragment {
	private ImageView mIv;
	private TextView mTv;
	private LineChart lineChart;
	private PieChart chart;
	private String startTime;
	private String endTime;
	private boolean isEmpty=true;

	@Override
	public void onCreate(@Nullable Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	@Override
	@Nullable
	public View onCreateView(LayoutInflater inflater,
			@Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_academic_analysis, null);
		initView(view);
		return view;
	}

	private void initView(View view) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy.M.d");
		Calendar calendar = Calendar.getInstance();

		if (calendar.get(Calendar.MONTH) + 1 <= 9) {
			startTime = (calendar.get(Calendar.YEAR) - 1) + ".9.1";
			endTime = format.format(calendar.getTime());
		} else {
			startTime = (calendar.get(Calendar.YEAR)) + ".9.1";
			endTime = format.format(calendar.getTime());
		}

		mIv = (ImageView) view.findViewById(R.id.acad_iv);
		mTv = (TextView) view.findViewById(R.id.acad_tv);
		lineChart = (LineChart)view. findViewById(R.id.lineChart);
		chart = (PieChart) view.findViewById(R.id.pieChart);
		
		initChart();
	}
	@SuppressLint("ResourceAsColor")
	private void initChart() {
		lineChart.getAxisLeft().setEnabled(false);
		lineChart.getAxisRight().setEnabled(false);
		lineChart.setDrawGridBackground(false);
		lineChart.setHighlightPerTapEnabled(false);
		lineChart.setDragDecelerationEnabled(false);
		lineChart.setDoubleTapToZoomEnabled(false);
		lineChart.setTouchEnabled(false);
		lineChart.setDragEnabled(false);
		lineChart.setPinchZoom(false);
		lineChart.setDragEnabled(false);
		lineChart.setDescription("");
		lineChart.setNoDataTextDescription("还没有相关的成绩记录");
		Paint paint=lineChart.getPaint(PieChart.PAINT_INFO);
		paint.setColor(Color.BLACK);
		lineChart.setPaint(paint, PieChart.PAINT_INFO);
		Legend l = lineChart.getLegend();
		l.setEnabled(false);
		setData(10, 20);

		loadPriaseData();

	}
	private void setData(int count, float range) {
		XAxis xAxis = lineChart.getXAxis();
		// 设置X轴的文字在底部
		xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
		// 模拟一个x轴的数据 12/1 12/2 ... 12/7
		ArrayList<String> xValues = new ArrayList<String>();
		for (int i = 0; i < count; i++) {
			xValues.add("12/" + i);
		}

		ArrayList<Entry> values = new ArrayList<Entry>();

		for (int i = 0; i < count; i++) {

			float val = (float) (Math.random() * range) + 3;
			values.add(new Entry(val, i));
		}

		LineDataSet set1;

		// create a dataset and give it a type
		set1 = new LineDataSet(values, "");
		set1.setColor(Color.parseColor("#2ECD71"));
		set1.setCircleColor(Color.parseColor("#2ECD71"));
		set1.setLineWidth(1f);
		set1.setCircleSize(5f);
		set1.setDrawCircleHole(true);
		set1.setValueTextSize(9f);
		set1.setLineWidth(4f);

		LineData data = new LineData(xValues, set1);

		// set data
		lineChart.setData(data);

	}

	/**
	 * 加载各个模块中所占的比例
	 */
	private void loadPriaseData() {
		showLoading();
		HashMap<String, Object> sendMap = new HashMap<String, Object>();
		sendMap.put("token", mSpUtil.getToken());
		sendMap.put("school_id", mSpUtil.getChildSchoolId());
		sendMap.put("grade_id", mSpUtil.getChildGradeId());
		sendMap.put("class_manager_id", mSpUtil.getChildClassId());
		sendMap.put("student_id", mSpUtil.getCurrentChildId());
		sendMap.put("start_date", startTime);
		sendMap.put("end_date", endTime);
		String requestUrl = ParamsUtils.buildParams(
				NetWorkApi.COMPREHENSIVE_API, sendMap);

		MyAsyncHttp.get(mActivity, requestUrl, new AsyncCallBackListener() {

			@Override
			public void onAsyncCallBack(RESULTCODE resuleCode, String request,
					String result) {
				hideLoading();
				if (resuleCode == RESULTCODE.SUCCESS) {
					ArrayList<GrowRewardAndMoveInfo> infos = ResponseUtils
							.getGrowStatisticsInfos(mActivity, result);
					if (infos != null && infos.size() > 0) {
						showChart(chart, infos);
					}
				}

			}

		});

	}

	private void showChart(PieChart pieChart,
			List<GrowRewardAndMoveInfo> statisticsList2) {

		PieData mPieData = getPieData(statisticsList2);

		pieChart.setDrawHoleEnabled(true);
		pieChart.setHoleColor(Color.TRANSPARENT);
		pieChart.setHoleRadius(80f);

		pieChart.setHoleColorTransparent(false);
		pieChart.setTransparentCircleRadius(0); // 半透明圈

		pieChart.setDescription("");
		pieChart.setDrawCenterText(true); // 饼状图中间可以添加文字
		pieChart.setCenterText("");

		pieChart.setRotationAngle(90); // 初始旋转角度
		pieChart.setRotationEnabled(false); // 可以手动旋转

		pieChart.setUsePercentValues(true); // 显示成百分比
		pieChart.setNoDataTextDescription("还没有发布相关的成长记录");
		Paint paint=pieChart.getPaint(PieChart.PAINT_INFO);
		paint.setColor(Color.BLACK);
		pieChart.setPaint(paint, PieChart.PAINT_INFO);
		pieChart.setDrawSliceText(false);
		pieChart.setExtraOffsets(0, 0, 80, 60);

		// 设置标注的信息
		Legend mLegend = pieChart.getLegend(); // 设置比例图
		mLegend.setPosition(LegendPosition.RIGHT_OF_CHART); // 最右边显示
		mLegend.setDirection(LegendDirection.LEFT_TO_RIGHT);
		mLegend.setTextColor(getResources().getColor(R.color.black));
		mLegend.setXEntrySpace(-7f);
		mLegend.setYEntrySpace(5f);

		// 设置比例块换行...
		mLegend.setWordWrapEnabled(true);
		mLegend.setDirection(Legend.LegendDirection.LEFT_TO_RIGHT);

		pieChart.animateXY(1000, 1000); // 设置动画
		// 设置数据
		pieChart.setData(mPieData);
		pieChart.invalidate();

	}

	/**
	 * 
	 * @param count
	 *            分成几部分
	 * @param range
	 */

	private PieData getPieData(List<GrowRewardAndMoveInfo> statisticsList) {

		ArrayList<String> xValues = new ArrayList<String>(); // xVals用来表示每个饼块上的内容
		ArrayList<Entry> yValues = new ArrayList<Entry>(); // yVals用来表示封装每个饼块的实际数据

		for (int i = 0; i < statisticsList.size(); i++) {
			if(!"0.00".equals(statisticsList.get(i).data)){
				isEmpty=false;
				
			}
			
		}
		if(!isEmpty){
			for (int i = 0; i < statisticsList.size(); i++) {
				xValues.add(statisticsList.get(i).desc);
				yValues.add(new Entry(NumberFormatUtil
						.getFloatFromString(statisticsList.get(i).data), i));
				
			}
		}
	

		// y轴的集合
		PieDataSet pieDataSet = new PieDataSet(yValues, "");// "Quarterly Revenue 2014"/*显示在比例图上*/);
		pieDataSet.setSliceSpace(0f);
		pieDataSet.setDrawValues(false);
		ArrayList<Integer> colors = new ArrayList<Integer>();

		// 饼图颜色
		colors.add(Color.rgb(250, 215, 51));
		colors.add(Color.rgb(241, 98, 68));
		colors.add(Color.rgb(109, 145, 255));
		colors.add(Color.rgb(209, 71, 229));
		colors.add(Color.rgb(58, 208, 171));
		colors.add(Color.rgb(101, 118, 163));
		colors.add(Color.rgb(203, 204, 205));
		colors.add(Color.rgb(90, 114, 100));
		if (yValues.size() > 8) {
			int r = 0;
			int g = 0;
			int b = 0;
			for (int i = 5; i < yValues.size(); i++) {
				r = (int) (Math.random() * 255 + 1);
				g = (int) (Math.random() * 255 + 1);
				b = (int) (Math.random() * 255 + 1);
				colors.add(Color.rgb(r, g, b));
			}
		}
		pieDataSet.setColors(colors);

		PieData pieData = new PieData(xValues, pieDataSet);

		pieData.setValueFormatter(new PercentFormatter());
		pieData.setValueTextSize(10f);
		pieData.setValueTextColor(getResources().getColor(R.color.white));

		return pieData;
	}
	@Override
	protected void onChoiceChildResult(ChildBean myChild) {
		// TODO Auto-generated method stub
		
	}

}